var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/businessComponent/grid/grid.tsx
var grid_exports = {};
__export(grid_exports, {
  Grid: () => Grid
});
module.exports = __toCommonJS(grid_exports);
var import_table = require("../../functionalComponent/table");
var import_util = require("../../util");
var defaultResponse = (res) => {
  if (res && res.hasOwnProperty("total")) {
    return res;
  } else if (res && res.hasOwnProperty("totalRows") && res.hasOwnProperty("Record")) {
    return { total: res.totalRows, list: res.Record };
  } else {
    return res || [];
  }
};
function filterRowByBusFields(row, busFields, keyValues, dataIndexMap, exclude = []) {
  const fields = busFields || Object.keys(row);
  const newData = {};
  fields.forEach((c) => {
    var _a;
    !exclude.includes(c) && (newData[c] = import_util.iup.convertData(row[c], (_a = dataIndexMap == null ? void 0 : dataIndexMap[c]) == null ? void 0 : _a.valueType));
  });
  newData.key = keyValues;
  return newData;
}
function flatRows(rows) {
  const tmpRows = [];
  rows == null ? void 0 : rows.forEach(({ children, __update__, ...row }) => {
    tmpRows.push(row);
    (children == null ? void 0 : children.length) && Array.prototype.push.apply(tmpRows, flatRows(children));
  });
  return tmpRows;
}
function areEqual(oldRow, newRow, exceptFields) {
  const oldKeys = Object.keys(oldRow).filter((k) => !exceptFields.includes(k));
  const newKeys = Object.keys(newRow).filter((k) => !exceptFields.includes(k));
  if (oldKeys.length !== newKeys.length) {
    return false;
  }
  return !newKeys.some((p) => {
    return import_util.iup.jsonString(newRow[p]) !== import_util.iup.jsonString(oldRow[p]);
  });
}
var Grid = (0, import_util.compHoc)(
  class extends import_util.IUPComponent {
    constructor(props) {
      super(props);
      this._initRows = void 0;
      this.busKey = props.busKey;
    }
    getBusKey() {
      return this.busKey || this._compIns.getApi(false).getKeyField();
    }
    /**
     * 获取子表的数据源属性
     */
    _getSubTableDataKeys(subTable) {
      return subTable ? Object.keys(subTable).map((id) => {
        return subTable[id].dataSource[0];
      }) : [];
    }
    _getSubTableDataIndexMap(id) {
      var _a;
      return ((_a = import_util.iup.getCmpApi(id)) == null ? void 0 : _a.getDataIndexMap()) || {};
    }
    _getSubKeyFields(id) {
      const api = import_util.iup.getCmpApi(id);
      if (api) {
        return [api.getCheckBoxDataIndex(), api.getExpandField()];
      }
      return [];
    }
    _loopSubTableByRowState(parent, subTable, rowState, oldParent) {
      if (subTable) {
        const subIds = Object.keys(subTable);
        if (subIds.length > 0) {
          const ret = { subTable: {} };
          const subTableDataKeys = this._getSubTableDataKeys(subTable);
          Object.keys(subTable).forEach((id) => {
            var _a, _b, _c;
            const rows = flatRows(parent[subTable[id].dataSource[0]]);
            const busKey = subTable[id].busKey || ((_a = import_util.iup.getCmpApi(id)) == null ? void 0 : _a.getProps().busKey) || ((_b = import_util.iup.getCmpApi(id)) == null ? void 0 : _b.getKeyField());
            if (rowState === "modifiedRow") {
              const oldRows = flatRows(oldParent == null ? void 0 : oldParent[subTable[id].dataSource[0]]);
              ret.subTable[id] = this._getResultTable({
                newRows: rows,
                oldRows,
                busKey,
                exceptFields: this._getSubKeyFields(id),
                dataIndexMap: this._getSubTableDataIndexMap(id),
                subTable: (_c = import_util.iup.getCmpApi(id)) == null ? void 0 : _c.getProps().subTable
              });
            } else {
              ret.subTable[id] = {
                isChanged: rowState !== "unChangedRow" && rows.length > 0,
                table: {
                  key: busKey,
                  [rowState]: rows.map((row) => {
                    var _a2, _b2;
                    return {
                      row: filterRowByBusFields(
                        row,
                        subTable[id].busFields || ((_a2 = import_util.iup.getCmpApi(id)) == null ? void 0 : _a2.getProps().busFields),
                        null,
                        this._getSubTableDataIndexMap(id),
                        [this._getSubKeyFields(id), ...subTableDataKeys]
                      ),
                      ...this._loopSubTableByRowState(row, (_b2 = import_util.iup.getCmpApi(id)) == null ? void 0 : _b2.getProps().subTable, rowState)
                    };
                  })
                }
              };
            }
          });
          return ret;
        }
      }
      return {};
    }
    _getResultTable({ newRows, oldRows, busKey, exceptFields, dataIndexMap, subTable, ignoreUnChanged = false }) {
      const subTableDataKeys = this._getSubTableDataKeys(subTable);
      let busKeys = import_util.iup.isSymbol(busKey) ? [busKey] : import_util.iup.split(busKey);
      const filterFields = [...exceptFields, ...subTableDataKeys];
      const result = {
        isChanged: false,
        table: {
          key: busKey,
          unChangedRow: [],
          modifiedRow: [],
          newRow: [],
          deletedRow: []
        }
      };
      const oldMap = /* @__PURE__ */ new Map();
      oldRows.forEach((r) => {
        const values = busKeys.reduce((p, c) => {
          if (!import_util.iup.isNullOrEmpty(r[c]) && !(r[c] + "").endsWith("_$_")) {
            p.push(r[c]);
          }
          return p;
        }, []);
        values.length === busKeys.length && oldMap.set(values.join(","), r);
      });
      newRows.forEach((dataRow) => {
        const values = busKeys.reduce((p, c) => {
          p.push(dataRow[c] ?? "");
          return p;
        }, []).join(",");
        if (oldMap.has(values)) {
          const oldRow = oldMap.get(values);
          if (areEqual(oldRow, dataRow, exceptFields)) {
            !ignoreUnChanged && result.table.unChangedRow.push({
              row: filterRowByBusFields(dataRow, this.props.busFields, values, dataIndexMap, filterFields),
              ...this._loopSubTableByRowState(dataRow, subTable, "unChangedRow")
            });
          } else {
            result.table.modifiedRow.push({
              row: filterRowByBusFields(dataRow, this.props.busFields, values, dataIndexMap, filterFields),
              ...this._loopSubTableByRowState(dataRow, subTable, "modifiedRow", oldRow)
            });
          }
          oldMap.delete(values);
        } else {
          result.table.newRow.push({
            row: filterRowByBusFields(dataRow, this.props.busFields, null, dataIndexMap, [...busKeys, ...filterFields]),
            ...this._loopSubTableByRowState(dataRow, subTable, "newRow")
          });
        }
      });
      oldMap.forEach((row) => {
        result.table.deletedRow.push({
          row: filterRowByBusFields(
            row,
            this.props.busFields,
            busKeys.map((k) => row[k] || "").join(","),
            dataIndexMap,
            filterFields
          ),
          ...this._loopSubTableByRowState(row, subTable, "deletedRow")
        });
      });
      ["newRow", "modifiedRow", "deletedRow", "unChangedRow"].forEach((key) => {
        if (result.table[key].length === 0) {
          delete result.table[key];
        } else if (key !== "unChangedRow") {
          result.isChanged = true;
        }
      });
      if (ignoreUnChanged) {
        delete result.table.unChangedRow;
      }
      return result;
    }
    /**
     * 返回行状态全是新增的json格式数据【返回格式同ExtUx.js的GetAllGridData方法】
     */
    getAllDataForNew(simple = true) {
      const { subTable } = this.props;
      const { getStore, getDataIndexMap, getKeyField } = this._compIns.getApi(false);
      const [store, dataIndexMap, keyField, subTableDataKeys] = [
        getStore(),
        getDataIndexMap(),
        getKeyField(),
        this._getSubTableDataKeys(subTable)
      ];
      const rows = flatRows(store.data);
      return {
        isChanged: rows.length > 0,
        table: {
          key: this.getBusKey(),
          newRow: rows.map((row) => {
            return {
              row: filterRowByBusFields(row, this.props.busFields, null, dataIndexMap, [keyField, ...subTableDataKeys]),
              ...this._loopSubTableByRowState(row, subTable, "newRow")
            };
          })
        }
      };
    }
    /**
     * 返回所有数据行，包含行状态
     */
    getAllData(ignoreUnChanged = false) {
      const { subTable } = this.props;
      const { getStore, getDataIndexMap, getCheckBoxDataIndex, getExpandField } = this._compIns.getApi(false);
      const [store, dataIndexMap, checkDataIndex, expandField] = [
        getStore(),
        getDataIndexMap(),
        getCheckBoxDataIndex(),
        getExpandField()
      ];
      const [raw, data] = [flatRows(this._initRows || store.raw), flatRows(store.data)];
      return this._getResultTable({
        newRows: data,
        oldRows: raw,
        busKey: this.getBusKey(),
        exceptFields: [checkDataIndex, expandField],
        dataIndexMap,
        subTable,
        ignoreUnChanged
      });
    }
    /**
     * 返回更新的行
     */
    getChange({ initRows, flatSubTable = true, ignoreUnChanged = true, simple = true } = {}) {
      var _a;
      const { subTable } = this.props;
      this._initRows = initRows;
      if (subTable && flatSubTable) {
        return this._getChangeBySubTableMerge(ignoreUnChanged);
      }
      const result = this.getAllData(ignoreUnChanged);
      if (subTable && result.isChanged && ignoreUnChanged) {
        (_a = result.table.modifiedRow) == null ? void 0 : _a.forEach((r) => {
          if (r.subTable) {
            Object.keys(r.subTable).forEach((subName) => {
              delete r.subTable[subName].table.unChangedRow;
            });
          }
        });
      }
      if (simple) {
        return Object.keys(result.table).reduce((prev, key) => {
          const data = result.table[key];
          if (import_util.iup.isArray(data)) {
            prev[key] = data.map(({ row }) => row);
          }
          return prev;
        }, {});
      }
      return result;
    }
    /**
     * 返回更新的行
     */
    _getChangeBySubTableMerge(ignoreUnChanged = true) {
      const { subTable } = this.props;
      const result = this.getAllData(ignoreUnChanged);
      if (subTable && (result.isChanged || !ignoreUnChanged)) {
        const ret = {
          isChanged: true,
          table: { key: result.table.key },
          subTable: {}
        };
        const keys = ["newRow", "modifiedRow", "deletedRow"];
        !ignoreUnChanged && keys.push("unChangedRow");
        keys.forEach((mKey) => {
          if (result.table.hasOwnProperty(mKey)) {
            ret.table[mKey] = result.table[mKey].map((r) => {
              if (r.subTable) {
                Object.keys(r.subTable).forEach((subName) => {
                  ret.subTable[subName] = ret.subTable[subName] || {
                    isChanged: false,
                    table: { key: r.subTable[subName].table.key }
                  };
                  keys.forEach((dKey) => {
                    const subData = r.subTable[subName].table;
                    if (subData.hasOwnProperty(dKey)) {
                      const data = ret.subTable[subName].table[dKey] || [];
                      Array.prototype.push.apply(data, subData[dKey]);
                      if (data.length > 0) {
                        ret.subTable[subName].isChanged = true;
                        ret.subTable[subName].table[dKey] = data;
                      }
                    }
                  });
                });
              }
              return { row: r.row };
            });
          }
        });
        return ret;
      }
      return result;
    }
    /**
     * 数据源是否变化
     */
    isChanged() {
      return this.getAllData(true).isChanged;
    }
    render() {
      const { busKey, busFields, ...props } = this.props;
      return /* @__PURE__ */ React.createElement(import_table.Table, { ref: this.outRef, cacheRaw: true, response: defaultResponse, ...props });
    }
  },
  "Grid"
);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  Grid
});
